/**
 * init
 */
import Toast from 'toon-ui/lib/components/toast';
/**
 * 随机高度，随机图片，布局函数
 */

var wf = {
  // 返回随机高宽的图片
  rdmImg: function () {
    var width = Math.floor(Math.random() * 100) + 300,
      height = Math.floor(Math.random() * 500) + 300;
    return "http://placekitten.com/" + height + '/' + width;
  },
  // 进行排列
  arrange: function (index,isStayTop,scrollTop) {
    var colsHeight = [0, 0];
    var lastColsHeight = 0;
    let itemWidth = 186;
    // 计算出列
    let cols = 2;
    $(".photo-container").each(function (e) {
      let col = 0, style = "";
      // 获取第一个容器的宽
      if (colsHeight[0] <= colsHeight[1]) {
        col = 0;
        style = 'left:' + (col * itemWidth) + 'px;';
      } else {
        col = 1;
        style = 'left:' + (col * itemWidth + 3) + 'px;';
      }
      style += "top :" + colsHeight[col] + "px;"
      $(this).attr("style", style);
      colsHeight[col] += $(this).height();
      var more = document.getElementById("mainScrolldroploadDOM");
      if(colsHeight[col]>lastColsHeight){
        more.style.top = ( colsHeight[col] +10 ) + "px";
        lastColsHeight = colsHeight[col];
      }

    });
    // //返回列表页定位
    // if(isStayTop){
    //   if(scrollTop){
    //     document.getElementById('mainScroll').scrollTop = scrollTop;
    //     document.getElementById('mainScroll').style.opacity = 1;
    //   }else if(scrollTop == 0){
    //     document.getElementById('mainScroll').scrollTop = 0;
    //     document.getElementById('mainScroll').style.opacity = 1;
    //   }
    // }
  },
}



export default {
  data() {
    return {
      subData:{
      // 加载更多
      load: false,
      // 是否有新评论
      hasComment: false,
      // 图片组
      photos: false,
      // 图片张数
      photosNum: '',
      // 当前页
      pageNum: 1,
      // 当前页
      curPage: 0,
      // 每页条数
      pageSize: 10,
      // 显示数据
      showData: false,
      // 专题详情
      subjectContent:{
        picUrl:'',
        detailContent:'',

      },
      //专题id
      subjectId:'',
      //专题名称
      subjectName:'',
      //提示文案，传给发布页面
      hint:'',
      //是否显示操作按钮
      showActionFlag:false,
      }
    }
  },
  filters: {
    thumbnail: function (url, param) {
      return url.replace(".png", param + ".png").replace(".jpg", param + ".jpg")
    },
    /**
     * @description 返回18个字符  如果超过18个 追加...
     */
    subStrings: function (str,subjectName) {
      str = str.replace(/[\r\n]{1,}/g,"　").replace(/[\r\n]$/g,'');
      let len;
      if(subjectName){
        len = subjectName.length;
      }else{
        len = 0;
      }
      return (len+str.length) > 18 ? str.substr(0, 18-len) + '...' : str
    },
    /**
     * 0 => 赞
     */
    changeVote: function (num) {
      return num > 0 ? num  > 9999 ? (num/10000).toFixed(1).replace('.0', '') + 'W' : num : '赞'
    },
    /**
    * 0 => 评论
    */
    changeDis: function (num) {
       return num > 0 ? num  > 9999 ? (num/10000).toFixed(1).replace('.0', '') + 'W' : num : '评论'
    },
  },
  beforeRouteEnter(to, from, next) {
    if(from.name !='detailPraising' && from.name !='detailReport'){
      sessionStorage.removeItem('scrollTop-subject');
      sessionStorage.removeItem('counts');
      sessionStorage.setItem('isFirstIn',true);
    }else{
      sessionStorage.setItem('isFirstIn',false);

    }

    next();
  },
  mounted() {
    //if(!this.$util.sessionData('isFirstIn')){
      this.init();
    //}

    document.getElementById('mainScroll').addEventListener('scroll',this.hideAction);
  },
  watch:{
    "$route":'init'
  },
  activated(){
    this.$util.setTitle(this.subData.subjectName+'专题');
    this.subData.showActionFlag = false;
    this.getCommentStatus();
    //初始化
    // if(this.$util.sessionData('isFirstIn')){
    //   this.init();
    //   }else {
    //   this.$util.setTitle(this.subData.subjectName+'专题');
    //   this.subData.showActionFlag = false;
    //   this.getCommentStatus();
    // }
    //高度定位
    if( this.$util.sessionData('scrollTop-subject')){
      document.getElementById('mainScroll').scrollTop = this.$util.sessionData('scrollTop-subject');
    }else if( this.$util.sessionData('scrollTop-subject') == '0'){
      document.getElementById('mainScroll').scrollTop = 0;
    }
    //同步列表点赞、评论数据
    if(this.$util.sessionData('counts')){
      let counts = JSON.parse(this.$util.sessionData('counts'));
      if(this.subData.photos[counts.index]){
        this.subData.photos[counts.index].praiseCount = counts.praiseCount;
        this.subData.photos[counts.index].commentCount = counts.commentCount;
        this.subData.photos[counts.index].praised = counts.praised;
      }

    }
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
    // this.$util.droploadUpOnScroll()
    if(to.name == 'detailPraising'||to.name == 'detailReport'){
      let scrollTop = document.getElementById('mainScroll').scrollTop;
      if(scrollTop){
        this.$util.sessionData('scrollTop-subject',scrollTop);
      }else if(scrollTop == 0){
        this.$util.sessionData('scrollTop-subject','0');
      }
    }else{
      this.$util.sessionData('scrollTop-subject','0');
    }
    next();
  },
  methods: {
    init(to,from) {
      if(to && to.name=='subjectList' &&  this.subData.subjectId != this.$route.params.subjectId ){
        //格式化数据

        this.subData={
          // 加载更多
          load: false,
            // 是否有新评论
            hasComment: false,
            // 图片组
            photos: false,
            // 图片张数
            photosNum: '',
            // 当前页
            pageNum: 1,
            // 当前页
            curPage: 0,
            // 每页条数
            pageSize: 10,
            // 显示数据
            showData: false,
            // 专题详情
            subjectContent:{
            picUrl:'',
              detailContent:'',

          },
          //专题id
          subjectId:'',
            //专题名称
            subjectName:'',
            //提示文案，传给发布页面
            hint:'',
            //是否显示操作按钮
            showActionFlag:false,
        }
        this.subData.subjectId = this.$route.params.subjectId;
        this.querySubjectDetail();
        this.getSubjectConvList();
        this.$util.droploadUpOnScroll( {ele: 'mainScroll'}, this.getSubjectConvList )

        this.getCommentStatus();

      }else if(!to){
        this.subData.subjectId = this.$route.params.subjectId;
        this.querySubjectDetail();
        this.getSubjectConvList();
        this.$util.droploadUpOnScroll( {ele: 'mainScroll'}, this.getSubjectConvList )

        this.getCommentStatus();
      }

    },

    /**
     * 获取有新评论的状态
     * /convphoto/getCommentStatus
     */
    getCommentStatus() {
      let _this = this;
      _this.$http.post('/convphoto/getCommentStatus', {}, {loading: false}).then(function (rep) {
        console.log(rep)
        if (rep.meta && rep.meta.code == '0') {
          _this.subData.hasComment = rep.data;
        }
      }).catch(function (err) {
        console.log(err)
      })
    },

    /**
     * 获取专题详情
     */
    querySubjectDetail() {
      let _this = this;
      var params = {
        "subjectId": _this.$route.params.subjectId,
      };
      this.$http.post("convSubject/querySubjectDetail", params).then(function (rep) {
        if (rep.meta && rep.meta.code == '0') {
          _this.subData.subjectContent = rep.data;
          _this.$util.setTitle(rep.data.subjectName+'专题');
          _this.subData.subjectName = rep.data.subjectName;
          _this.subData.hint= rep.data.hint;

        }else {
          Toast({
            message: rep.meta.message,
            duration: 1000, // 持续时间，默认3000毫秒
          });
        }
      }).catch(function (err) {
        // Toast({
        //   'message': '获取详情失败',
        //   'duration': 1000, // 持续时间，默认3000毫秒
        // });
      })
    },

    /**
     * 获取专题随手拍列表
     */
    getSubjectConvList() {
      //如果当前页==下一页则不发请求
      if (this.subData.pageNum == this.subData.curPage) {
        return
      } else {
        this.subData.curPage = this.subData.pageNum;
      }
      let _this = this;
      var params = {
        "pageNum": _this.subData.pageNum,
        "pageSize": _this.subData.pageSize,
        "subjectId":_this.subData.subjectId,
      };
      this.$http.post("/convSubject/getSubjectConvList", params).then(function (rep) {
        _this.loadHide = false;
        if (rep.meta && rep.meta.code == '0') {
          // 获取数据完成
          let datas = rep.data || [];
          if (!_this.subData.photos) {
            _this.subData.photos = []
          }
          if (datas.length > 0) {
            _this.loadImg(datas, 0);
          } else {
            _this.subData.showData = true
          }
           // 隐藏加载更多
          if(datas.length < _this.subData.pageSize) {
            _this.$util.droploadUpOnScroll( {ele: 'mainScroll', text: ' ', stop: true})
          }
        }
      }).catch(function (err) {
        console.log(err);
      })
    },


    /**
     * 排列组合
     */
    arrange(index) {
      let _this = this;
      if (_this.subData.photos[index] && _this.subData.photos[index].photo) {
        _this.subData.photos[index].photo = _this.subData.photos[index].photo.replace("_17_2048_1_0.png", "_290_2048_100_0.png").replace("_17_2048_1_0.jpg", "_290_2048_100_0.jpg");
        _this.subData.photos[index].load = true;
      }
      wf.arrange(index);
    },
    /**
     * 加载图片
     * @param {*} arr
     * @param {*} index
     */
    loadImg(arr, index) {
      let _this = this;
      let img = new Image();
      img.onerror = function () {
        nextImg();
        arr[index].load = true;
      };
      img.onload = nextImg;
      function nextImg() {
        _this.subData.photos.push(arr[index]);
        if (index < arr.length) {
          _this.loadImg(arr, index + 1);
          //是否有下一页
          if (index + 1 >= _this.subData.pageSize) {
            _this.subData.pageNum++;
          }
        }
      }
      if (arr[index] && arr[index].photo) {
        img.src = arr[index].photo.replace(".png", "_17_2048_1_0.png").replace(".jpg", "_17_2048_1_0.jpg");
        arr[index].photo = arr[index].photo.replace(".png", "_17_2048_1_0.png").replace(".jpg", "_17_2048_1_0.jpg")
        arr[index].load = false;
      }
    },

    /**
     * 点赞
     */
    praise(item) {
      let _this = this;
      let param = {
        "id": item.convId
      }
      _this.$http.post('/praisingCity/praise', param, {loading: false}).then(function (rep) {
        if (rep.meta && rep.meta.code == '0') {
          item.praised = !item.praised;
          if (item.praised) {
            item.praiseCount = item.praiseCount - 0 + 1;
          } else {
            item.praiseCount = item.praiseCount - 0 - 1;
          }
        }
      }).catch(function () {

      })
    },
    /**
     * 跳转详情
     */
    godetail(id,index,convType) {
    console.log(convType)
      if (convType == 2) {
          // 问题处理
          this.$router.push({ 'name': 'detailReport', params: { 'id': id},query:{'index':index } });
      } else {
          // 大赞北京  社会警示
          this.$router.push({ 'name': 'detailPraising', params: { 'id': id},query:{'index':index } });
      }

    },

    /**
     * 发起随手拍
     */
    goPhoto() {
      if(this.subData.subjectContent.isShelve =='1'){
          this.$router.push({ 'name': 'issue',query:{'hint':this.subData.hint,'subjectId':this.subData.subjectId}})
      }
    },
    /**
     * 跳转我的随手拍
     */
    goMyPhoto() {
      this.$router.push({ 'name': 'list' })
    },

  /**
   * 跳转专题详情页
   */
  goSubject(){
    //this.$router.go(0);
    window.location.reload();
    // let subjectId = this.subData.subjectId;
    // this.$router.go({'name':'subjectList',params: { 'subjectId': subjectId,'tmp':new Date().getTime() }})
  },
    /**
     * 显示操作按钮
     */
    showAction(){
      if(this.subData.showActionFlag == "active"){
        this.subData.showActionFlag = "unactive"
      }else{
        this.subData.showActionFlag = "active"
      }
    },
    hideAction(){
      if(this.subData.showActionFlag == "active"){
        this.subData.showActionFlag = "unactive"
      }
    }
  },
}
